package com.mark.org.service.impl;

import com.mark.basic.service.Impl.BaseServiceImpl;
import com.mark.org.domain.Department;
import com.mark.org.mapper.DepartmentMapper;
import com.mark.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author lenovo
 */
@Service

public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void add(Department dm) {
        departmentMapper.add(dm);// 返回自增id
        this.update(dm);
    }
    @Transactional
    @Override
    public void update(Department dm) {
        // 判断是否为顶级 1、顶级 2、非顶级
        // 新增顶级
        if(dm.getParent() == null){
            dm.setDirPath("/"+ dm.getId());
        }else {// 新增非顶级
            Department department = departmentMapper.listById(dm.getParent().getId());
            dm.setDirPath(department.getDirPath() +"/" + dm.getId());
        }
        departmentMapper.update(dm);
    }

    @Override
    public List<Department> queryTree() {
        // 查询所有的数据
        List<Department> deptAll = departmentMapper.listAll();
        System.out.println(deptAll);
        // 创建一个map集合HashMap   k 为Long类型  V 为Department
        HashMap<Long, Department> mapAll = new HashMap<>();
        // 遍历所有的数据放入hashmap中
        for (Department department : deptAll) {
            mapAll.put(department.getId(),department);
        }
//        System.err.println(mapAll);
        // 创建一个集合将parent为null的数据放入
        List<Department> firstlist = new ArrayList<>();
        // 遍历
        for (Department department : deptAll) {
            // 顶级
            if(department.getParent_id() == null){// 封装第一层级
                firstlist.add(department);
            }else {
                // mapAll.get(department.getParent_id())  ：通过k来获得V
                Department parent = mapAll.get(department.getParent_id());
                // 如果为空说明 没有下级，
                if(parent != null){
                    parent.getChildren().add(department);
                }
            }
        }
        System.err.println(firstlist);
        return firstlist;
    }
}